package com.yhzc.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 记录cookie的上次访问时间
 */
@WebServlet("/cookieDemo3")
public class CookieDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //第一次访问操作
        // 1 获取用户当前访问的时间
        Date date = new Date();
        //格式化时间数据(注意：在cookie值中不能使用分号（;）、逗号（,）以及空格，否则会出现异常)
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd/hh:mm:ss");
        String format1 = format.format(date);
        System.out.println(format1);
        // 3 将数据进行编码
        String encode = URLEncoder.encode(format1, "utf-8");
        // 4 将数据存入cookie
        Cookie cookie = new Cookie("time", encode);
        cookie.setMaxAge(60*60*24);
        // 5 将数据发送给浏览器
        response.addCookie(cookie);

        //第二次访问操作
        // 获取cookie数组
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            for (Cookie cookie2 : cookies) {
                //选择获取名称为time的cookie
                if("time".equals(cookie2.getName())) {
                    //由于数据之前经过编码，现在要还原的中文数据
                    String decode = URLDecoder.decode(cookie2.getValue(), "utf-8");
                    //将数据发送页面
                    response.setContentType("text/html;charset=utf‐8");
                    //将数据发送页面
                    response.getWriter().write(decode);
                }
            }
        }
    }
}
